const { Controller } = require("egg");

class TopicLessonController extends Controller {
  async list() {
    const { ctx, service } = this;

    const { topicId } = ctx.query;
    if (!topicId) {
      ctx.helper.error("缺少topicId参数");
      return;
    }

    try {
      const result = await service.topicLesson.list(topicId);
      ctx.helper.success(result);
    } catch (error) {
      ctx.helper.error(error);
    }
  }

  async create() {
    const { ctx, service } = this;

    // 简化参数结构，假设只有这些字段用于创建
    const { title, coverImage, desc, topicId } =
      ctx.request.body;
    const lessonData = {
      title,
      coverImage,
      desc,
      topicId,
    };

    try {
      const result = await service.topicLesson.create(lessonData);
      ctx.helper.success(result, "课程创建成功");
    } catch (error) {
      console.log(error, lessonData);
      ctx.helper.error(error);
    }
  }

  async delete() {
    const { ctx, service } = this;

    const { id } = ctx.request.body;

    try {
      const deleted = await service.topicLesson.delete(id);
      if (!deleted) {
        ctx.helper.success({ message: "课程删除成功" });
      } else {
        ctx.helper.error("课程记录不存在或已被删除");
      }
    } catch (error) {
      ctx.helper.error(error);
    }
  }

  async update() {
    const { ctx, service } = this;
    const { id, ...updateData } = ctx.request.body;

    try {
      const datas = await service.topicLesson.update(id, updateData);
      if (datas) {
        ctx.helper.success({ message: "课程更新成功" });
      } else {
        ctx.helper.error("课程记录不存在或无内容更新");
      }
    } catch (error) {
      console.log(error);
      ctx.helper.error(error);
    }
  }

  async id() {
    const { ctx, service } = this;

    const { id } = ctx.params;
    if (!id) {
      ctx.helper.error("缺少id参数");
      return;
    }

    try {
      const result = await service.topicLesson.id(id);
      ctx.helper.success(result);
    } catch (error) {
      ctx.helper.error(error);
    }
  }

  async startExam() {
    const { ctx, service } = this;

    let { lessonId } = ctx.request.body;

    lessonId = ctx.helper.toInt(lessonId);


    const status = await this.verify(lessonId);
    if (!status) {
      return ctx.helper.error(
        "您不是此系列课程的会员用户，请联系相关工作人员购买"
      );
    }

    try {

      const { questionCount } = await service.topicLesson.id(lessonId);

      const datas = await this.service.topicLessonQuestionBank.sortList(
        lessonId,
        questionCount
      );

      
      if (datas.length <= 0) {
        return ctx.helper.error("考试暂未发布试题，请联系工作人员发布试题");
      }

      console.log(datas, 'questionCount');


      const { userId } = await service.auth.getCurrentUser();

      const body = {
        lessonId,
        userId,
        exams: JSON.stringify(datas),
        answers: "[]",
      };

      const exams = await this.service.topicLessonExam.create(body);
      ctx.helper.success({
        exams,
        userId,
      });
    } catch (error) {
      ctx.helper.error(error);
    }
  }

  async endExam() {
    const { ctx, service } = this;

    const { examId, answers } = ctx.request.body;
    if (!examId) {
      ctx.helper.error("不存在examId");
      return;
    }

    if (!answers) {
      ctx.helper.error("不存在answers");
      return;
    }
    try {
      const params = {
        id: this.ctx.helper.toInt(examId),
        answers: JSON.stringify(answers),
      };
      const { exams, lessonId } =
        await service.topicLessonExam.updateAnswers(params);
      let num, percent;

      if (exams) {
        const res = await service.topicLessonExam.calcResult(exams, answers);
        if (res) {
          num = res.num;
          percent = res.percent;
        }

        const { passRate } = await service.topicLesson.id(lessonId);


        if (passRate > percent) {
          try {

            return ctx.helper.success({
              ...res,
              examsResult: {
                num,
                percent,
                status: 0,
                message: "考试未通过",
              },
            });
          } catch (error) {
            return ctx.helper.error(error);
          }
        } else {

          return ctx.helper.success({
            ...res,
            examsResult: {
              num,
              percent,
              status: 1,
              message: "考试通过~",
            },
          });
        }
      }
    } catch (error) {
      ctx.helper.error(error);
    }
  }

  async verify(lessonId) {

    const { userId } = await this.service.auth.getCurrentUser();

    console.log("userId", userId, lessonId)

    try {
      const res = await this.service.topicLessonPerson.verify({
        userId,
        lessonId,
      });

      return res;
    } catch (error) {
      return false;
    }
  }

  async checkIsVip() {
    const { ctx } = this;
    let { lessonId } = ctx.request.body;
    lessonId = ctx.helper.toInt(lessonId);

    const status = await this.verify(lessonId);

    if (!status) {
      return ctx.helper.error(
        "您不是此系列课程的会员用户，请联系相关工作人员购买"
      );
    } else {
      return ctx.helper.success("您是此系列课程的会员用户");
    }
  }

  async getUserStudyDuration() {

    let { lessonId } = this.ctx.query;

    if (!lessonId) {
      return this.ctx.helper.error("缺少lessonId参数");
    }
    lessonId = this.ctx.helper.toInt(lessonId);

    const { userId } = await this.service.auth.getCurrentUser();

    const datas = await this.service.topicLessonVideo.list(lessonId);

    const videoIds = datas.map(item => item.id);

    const res = await this.service.topicLessonVideoLogs.getUserDuration({ userId, videoIds});



    return this.ctx.helper.success(res);


  }
}

module.exports = TopicLessonController;
